import subprocess

"""
    @brief cjpm 编译指定路径项目
    @param path 路径
    @return 控制台数据
""" 
def cjpm_build_proj(path):
    # 使用 shell=True 并传递字符串命令
    command  = f"cd {path} &&"
    command += "cjpm update &&"
    command += "cjpm build"
    result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding='utf-8')
    return {
        "returncode":result.returncode,
        "stdout":result.stdout,
        "stderr":result.stderr
    }

"""
    @brief cjpm 编译指定路径项目并且打印输出
    @param path 路径
    @return 是否成功
"""
def cjpm_build_proj_print(path):
    retv = False
    result = cjpm_build_proj(path)
    if result["returncode"] == 0:
        print(result["stdout"])
        retv = True
    else:
        print(result["stderr"])
        retv = False
    return retv

"""
    @brief cjpm 测试指定路径项目
    @param path 路径
    @return 控制台数据
""" 
def cjpm_test_proj(path):
    # 使用 shell=True 并传递字符串命令
    command  = f"cd {path} &&"
    #command += "cjpm update &&"
    #command += "cjpm build &&"
    command += "cjpm test"
    result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding='utf-8')
    return {
        "returncode":result.returncode,
        "stdout":result.stdout,
        "stderr":result.stderr
    }

"""
    @brief cjpm 测试指定路径项目并且打印输出
    @param path 路径
    @return 是否成功
"""
def cjpm_test_proj_print(path):
    retv = False
    result = cjpm_test_proj(path)
    if result["returncode"] == 0:
        print(result["stdout"])
        retv = True
    else:
        print(result["stderr"])
        retv = False
    return retv

"""
    @brief cjpm 编译指定路径项目
    @param path 路径
    @return 控制台数据
""" 
def cjpm_execute_wait_proj(path):
    result = subprocess.run(path, shell=False, capture_output=True, text=True, encoding='utf-8')
    return {
        "returncode":result.returncode,
        "stdout":result.stdout,
        "stderr":result.stderr
    }

"""
    @brief cjpm 编译指定路径项目，并且执行等待结束
    @param path 路径
    @return 控制台数据
"""
def cjpm_build_proj_execute_wait(path):
    retv = False
    result = cjpm_build_proj(path)
    if result["returncode"] == 0:
        print(result["stdout"])
        result = cjpm_execute_wait_proj(path + "\\target\\release\\bin\\main.exe")
        if result["returncode"] == 0:
            print(result["stdout"])
            retv = True
        else:
            print(result["stderr"])
            retv = False

    else:
        print(result["stderr"])
        retv = False
    return retv